package com.ms.oschina.fragment;

import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ms.oschina.R;
import com.ms.oschina.adapter.ExpressionAdapter;
import com.ms.oschina.adapter.ExpressionAdapter.OnExpressionSelectListener;
import com.ms.oschina.base.BaseFragment;
import com.ms.oschina.util.LogUtils;
import com.ms.oschina.util.UiUtils;

public class ExpressionFragment extends BaseFragment implements OnClickListener {
	private ViewPager vpExpression;
	private TextView tvExpressionQq;
	private TextView tvExpressionEmoji;
	private ImageView ivExpressionDelete;
	private ExpressionAdapter adapter;
	private OnExpressionSelectListener listener;
	private EditText editText;

	/**
	 * 
	 * @param listener
	 *            当表情被点击时时的监听器
	 */
	public ExpressionFragment(OnExpressionSelectListener listener) {
		super();
		this.listener = listener;
	}

	private void findViews(View view) {
		vpExpression = (ViewPager) view.findViewById(R.id.vp_expression);
		tvExpressionQq = (TextView) view.findViewById(R.id.tv_expression_qq);
		tvExpressionEmoji = (TextView) view
				.findViewById(R.id.tv_expression_emoji);
		ivExpressionDelete = (ImageView) view
				.findViewById(R.id.iv_expression_delete);
	}

	@Override
	public int getLayoutId() {
		return R.layout.fragment_expression;
	}

	@Override
	public void initView(View view) {
		findViews(view);
	}

	@Override
	protected void initData() {
		tvExpressionEmoji.setOnClickListener(this);
		tvExpressionQq.setOnClickListener(this);
		ivExpressionDelete.setOnClickListener(this);
		adapter = new ExpressionAdapter(listener);
		vpExpression.setAdapter(adapter);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_expression_delete:
			int selectionStart = editText.getSelectionStart();// 获取光标的位置
			String text = editText.getText().toString();
			if (selectionStart == 0) {
				return;
			}
			if (TextUtils.isEmpty(text)) {
				return;
			}

			int lastIndexOfLeft = text.lastIndexOf("[");
			int lastIndexOfRight = text.lastIndexOf("]");
			
			int length = text.length();
			if ((length-1)==lastIndexOfRight && lastIndexOfLeft != -1 && lastIndexOfRight > lastIndexOfLeft) {
				//nothing
			} else {// 说明表情不存在
				lastIndexOfLeft = length - 1;
			}
			editText.getEditableText().delete(lastIndexOfLeft, selectionStart);
			// editText.setText(text);没有表情了，全是符号
			break;
		case R.id.tv_expression_emoji:
			vpExpression.setCurrentItem(1);
			break;
		case R.id.tv_expression_qq:
			vpExpression.setCurrentItem(0);
			break;
		}
	}

	/**
	 * 设置删除事件被点击时操作的editText
	 * 
	 * @param etNewsdetailCommentContent
	 */
	public void setDelEditText(EditText etNewsdetailCommentContent) {
		this.editText = etNewsdetailCommentContent;
	}
}
